package com.agriculture.entity;

import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonProperty;
import org.hibernate.annotations.CreationTimestamp;
import org.locationtech.jts.geom.Coordinate;
import org.locationtech.jts.geom.Polygon;

import javax.persistence.*;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Entity
@Table(name = "geo_parcel")
public class GeoParcel {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Integer id;

    @Column(name = "parcel_name", nullable = false)
    private String parcelName;

    @Column(columnDefinition = "GEOMETRY", nullable = false)
    @JsonIgnore
    private Polygon parcelBoundary;

    private Double area;

    @Column(name = "soil_type")
    private String soilType;

    @CreationTimestamp
    @Column(name = "created_time", updatable = false)
    private LocalDateTime createdTime;

    // Getters and Setters
    public Integer getId() { return id; }
    public void setId(Integer id) { this.id = id; }
    public String getParcelName() { return parcelName; }
    public void setParcelName(String parcelName) { this.parcelName = parcelName; }
    @JsonIgnore
    public Polygon getParcelBoundary() { return parcelBoundary; }
    public void setParcelBoundary(Polygon parcelBoundary) { this.parcelBoundary = parcelBoundary; }
    
    @JsonProperty("parcelBoundary")
    public Map<String, Object> getParcelBoundaryForJson() {
        if (parcelBoundary == null) return null;
        
        Map<String, Object> boundary = new HashMap<>();
        List<List<Map<String, Double>>> coordinates = new ArrayList<>();
        
        // 获取外环坐标
        Coordinate[] coords = parcelBoundary.getExteriorRing().getCoordinates();
        List<Map<String, Double>> ring = new ArrayList<>();
        
        for (Coordinate coord : coords) {
            Map<String, Double> point = new HashMap<>();
            point.put("x", coord.x);
            point.put("y", coord.y);
            ring.add(point);
        }
        
        coordinates.add(ring);
        boundary.put("coordinates", coordinates);
        
        return boundary;
    }
    public Double getArea() { return area; }
    public void setArea(Double area) { this.area = area; }
    public String getSoilType() { return soilType; }
    public void setSoilType(String soilType) { this.soilType = soilType; }
    public LocalDateTime getCreatedTime() { return createdTime; }
    public void setCreatedTime(LocalDateTime createdTime) { this.createdTime = createdTime; }
}